#!/usr/bin/env python
"""
更新所有任务执行记录的 duration 字段

此脚本用于修复数据库中已有的任务执行记录，计算并更新 duration 字段
"""
import sys
import os

# 添加项目根目录到 Python 路径
sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.dirname(__file__))))

from services.shared.database import TaskExecution
from services.shared.db_pool import get_db_session, close_db_session
from services.shared.logger import get_logger

# 获取日志记录器
logger = get_logger('scripts.update_all_durations')

def update_all_durations():
    """更新所有任务执行记录的 duration 字段"""
    logger.info("开始更新所有任务执行记录的 duration 字段")
    
    # 使用 db_pool 获取数据库会话
    session = get_db_session()
    try:
        # 查询所有已完成但 duration 为空的执行记录
        executions = session.query(TaskExecution).filter(
            TaskExecution.completed_at.isnot(None),
            TaskExecution.started_at.isnot(None)
        ).all()
        
        logger.info(f"找到 {len(executions)} 条执行记录需要检查")
        
        updated_count = 0
        for execution in executions:
            if execution.completed_at and execution.started_at:
                # 如果 duration 为空或为 0，重新计算
                if execution.duration is None or execution.duration == 0:
                    old_duration = execution.duration
                    execution.duration = (execution.completed_at - execution.started_at).total_seconds()
                    updated_count += 1
                    logger.debug(f"更新执行记录 ID: {execution.id}, 执行 ID: {execution.execution_id}, "
                               f"旧 duration: {old_duration}, 新 duration: {execution.duration}")
        
        if updated_count > 0:
            logger.info(f"提交更新，共更新 {updated_count} 条执行记录")
            session.commit()
            print(f'已更新 {updated_count} 条执行记录的 duration 字段')
        else:
            logger.info("没有执行记录需要更新 duration 字段")
            print('没有执行记录需要更新 duration 字段')
    finally:
        # 关闭数据库会话
        session.close()
        close_db_session()
        logger.info("数据库会话已关闭")

if __name__ == '__main__':
    update_all_durations()